﻿using MobaCommon.Code;
using MobaCommon.Dto;
using MobaCommon.OpCode;
using MOBAServer.Cache;
using MOBAServer.Room;
using Photon.SocketServer;
using System;
using System.Collections.Generic;
using System.Text;
using LitJson;

namespace MOBAServer.Logic
{
    public class FightHandler : IOpHandler
    {
        #region 缓存层
        public FightCache fightCache
        {
            get {
                return Caches.Fight;
            }
        }
        public PlayerCache playerCache
        {
            get {
                return Caches.Player;
            }
        }
        #endregion


        public void OnDisconnect(MobaClient client)
        {
            fightCache.Offline(client,playerCache.GetId(client));
        }

        public void OnRequest(MobaClient client, byte subCode, OperationRequest request)
        {
            switch(subCode)
            {
                case OpFight.Enter:
                    OnEnter(client,(int)request[0]);
                    break;
                case OpFight.Walk:
                    OnWalk(client, (float)request[0], (float)request[1],(float)request[2]);
                    break;

                default:break;
            }
        }
        /// <summary>
        /// 玩家移动
        /// </summary>
        /// <param name="client">客户端</param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        private void OnWalk(MobaClient client,float x,float y,float z)
        {
            int playerId = playerCache.GetId(client);
            FightRoom fightRoom= fightCache.GetRoom(playerId);
            if (fightRoom == null)
                return;
            fightRoom.Broast(OpCode.FightCode,OpFight.Walk,0,"有玩家移动",null,playerId,x,y,z);

        }
        private void OnEnter(MobaClient client,int playerId)
        {
            FightRoom room = fightCache.Enter(playerId,client);
            if (room == null)
                return;

            //首先要判断是否全部进入了
            //作用：保证竞技游戏的公平
            if (!room.IsAllEnter)
                return;
            //给每一个客户端发送战斗房间的信息
            room.Broast(OpCode.FightCode,OpFight.GetInfo,0,"加载战斗场景",null,
                JsonMapper.ToJson(room.Heros), 
                JsonMapper.ToJson(room.Towers));
        }

        public void StartFight(List<SelectModel> team1,List<SelectModel> team2)
        {
            fightCache.StartFight(team1,team2);
        }
    }
}
